//
//  HPCardIdentifyViewController.m
//  HPZZTong
//
//  Created by wenjun on 14-5-20.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPCardIdentifyViewController.h"
#import "HPBorderView.h"
#import "HPConditionTextField.h"
#import "ZZTongUtility.h"
#import "HPFastTransferViewController.h"
#import <HandPaySwiperModule/HandPaySwiperModule.h>

@interface HPCardIdentifyViewController ()
{
    IBOutlet UILabel * _cardNoLabel;
    IBOutlet UILabel * _amountLabel;
    IBOutlet HPConditionTextField * _usernameField;
    IBOutlet HPConditionTextField * _idNumberField;
    IBOutlet HPConditionTextField * _phoneField;
    IBOutlet UIButton * _statusSwitch;
    IBOutlet UIButton * _submitBtn;
    IBOutlet HPBorderView * _borderView;
}

@end

@implementation HPCardIdentifyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    self.title = @"转出卡实名认证";
    [super viewDidLoad];
    
    [_usernameField setConditionType:HPConditionType_Deafult];
    [_idNumberField setConditionType:HPConditionType_ASCII];
    [_phoneField setConditionType:HPConditionType_PositiveInteger];
    
    [_idNumberField setMaxLength:18];
    [_phoneField setMaxLength:11];
    
    [_submitBtn setBackgroundImage:[[UIImage imageNamed:@"bluebutton.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateNormal];
    [_submitBtn setBackgroundImage:[[UIImage imageNamed:@"bluebuttonhover.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateHighlighted];
    _borderView.clipsToBounds = NO;
    _borderView.borderType = BorderTypeDashed;
    _borderView.dashPattern = 4;
    _borderView.spacePattern = 4;
    _borderView.borderWidth = 1;
    _borderView.cornerRadius = 10;
    _borderView.borderColor = UIColorFromRGB(0x85BAF8);
    
    [_borderView refresh];
    
    _cardNoLabel.text = [Utility encryptCardID:[self.screenData objectForKey:@"cardNo"]];
    _amountLabel.text = [self.screenData objectForKey:@"amount"];
    
    [(UIScrollView *)self.view setContentSize:CGSizeMake(self.view.bounds.size.width, _submitBtn.frame.origin.y + 67)];
    
    self.view.backgroundColor = kNormalBackgroundColor;
    
//    [NOTIFICATION addObserver:self selector:@selector(swiperStateChanged:) name:SwiperStateChangeNotificationKey object:nil];
    self.canSave = NO;
}

//- (void)swiperStateChanged:(NSNotification *)notification
//{
//    NSNumber* tempState = (NSNumber*)notification.object;
//    SwiperState swiperState = (SwiperState) [tempState integerValue];
//    if (swiperState == SwiperStateNoDeviceDected)
//    {
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }
//}

- (IBAction)switchClicked
{
    _statusSwitch.selected = !_statusSwitch.selected;
}

- (BOOL)checkInput
{
    if (![ZZTongUtility checkName:_usernameField.text tips:@"户主姓名"])
    {
        [_usernameField becomeFirstResponder];
        return NO;
    }
    if (![ZZTongUtility checkIsInput:_idNumberField tips:@"户主身份证号码"])
    {
        [_idNumberField becomeFirstResponder];
        return NO;
    }
    if (![ZZTongUtility checkIDCard:_idNumberField.text tips:@"请输入正确的身份证号码"])
    {
        [_idNumberField becomeFirstResponder];
        return NO;
    }
    if (![ZZTongUtility checkIsInput:_phoneField tips:@"户主手机号码"])
    {
        [_phoneField becomeFirstResponder];
        return NO;
    }
    if (![ZZTongUtility checkMobile:_phoneField.text tips:@"请输入正确的手机号码"])
    {
        [_phoneField becomeFirstResponder];
        return NO;
    }
    return YES;
}

- (IBAction)submitBtnClicked
{
    if ([self checkInput])
    {
        [self addFourElements];
    }
}


- (void)addFourElements
{
    ZZTongClientEngine* zztEngine = [ZZTongClientEngine sharedInstance];
    [zztEngine.uiEngine showNetWaiting];
    
    //test
//    [self performSelector:@selector(cardIdentifySuccessed) withObject:nil afterDelay:2];
//    return;
    
    NSDictionary* params = @{
                             KEY_CHANNEL: [zztEngine getChannel],
                             KEY_CSN: [HPSwiperContext sharedInstance].connectedDeviceCSN,
                             @"cardNum": DES_ENC([self.screenData objectForKey:@"cardNo"]),
                             @"idNum": DES_ENC(_idNumberField.text),
                             @"mobileNum": DES_ENC(_phoneField.text),
                             @"userName": DES_ENC(_usernameField.text),
                             @"isSave": _statusSwitch.selected ? @"1" : @"0"
                             };
    
    [zztEngine.netEngine sendRequest:NET_ACTION_ADD_FOUR_ELEMENTS withParams:params withDelegate:self];
    
}

- (void)cardIdentifySuccessed
{
    UINavigationController* curNav = [ZZT_UIENG getCurrentNavigation];
    HPFastTransferViewController * transferController = [curNav.viewControllers objectAtIndex:curNav.viewControllers.count - 2];
    [transferController cardIdentifySuccessed];
}


- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData
{
    if ([action isEqualToString:NET_ACTION_ADD_FOUR_ELEMENTS])
    {
        [self cardIdentifySuccessed];
    }
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg
{
    [HPUIENG showAlert:msg];
}

- (NSString *)slipCardNumber:(NSString *)cardNumber secure:(BOOL)secure
{
    if (cardNumber.length >= 4)
    {
        NSString * str1 = [cardNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSMutableString * string = [[NSMutableString alloc] init];
        NSInteger index = 0;
        while (index < str1.length)
        {
            if (index + 4 >= str1.length)
            {
                [string appendString:[str1 substringWithRange:NSMakeRange(index, str1.length - index)]];
            }
            else
            {
                if (secure && index != 0)
                {
                    [string appendString:@"****"];
                }
                else
                {
                    [string appendString:[str1 substringWithRange:NSMakeRange(index, 4)]];
                }
                [string appendString:@" "];
            }
            index += 4;
        }
        return string;
    }
    return cardNumber;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
